package com.rslai.commons.validator.jsonvalidator.matchers;

import org.hamcrest.Description;
import org.hamcrest.Factory;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;

/**
 * 正则Matcher
 */
public class RegexMatcher extends TypeSafeMatcher<String> {
    private final String regex;

    /**
     * 构造函数
     * @param regex 正则
     */
    public RegexMatcher(String regex){
        this.regex = regex;
    }

    /**
     * 安全匹配，将永远不会为空
     * @param str 匹配内容
     * @return boolean
     */
    @Override
    public boolean matchesSafely(String str) {
        return str != null && str.matches(regex);
    }

    /**
     * 产生描述
     * @param description 描述
     */
    @Override
    public void describeTo(Description description) {
        description.appendText("matches regex ").appendValue(regex);
    }

    @Factory
    public static Matcher<String> matches(String regex) {
        return new RegexMatcher(regex);
    }

}